import {Buffer} from "buffer";
import {AxdrOptional} from "../asn1.axdr/AxdrOptional";
import {TimeTag} from "./TimeTag";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";


export class FjCAPdu implements AxdrType{

    dataCode : Buffer | null = null;
    timeTag : AxdrOptional<TimeTag> = new AxdrOptional<TimeTag>(new TimeTag(), false);

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_timeTag(timeTag : TimeTag){
        this.timeTag.setValue(timeTag);
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;
        this.timeTag = new AxdrOptional<TimeTag>(new TimeTag(), false);
        codeLength += this.timeTag.decode(input);
        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.timeTag != null){
                codeLength = 0;
                codeLength += this.timeTag.encode(output);
            }else{
                throw new Error("timeTag is null");
            }
        }
        console.log(codeLength);
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString() : string{
        if(this.timeTag != null){
            return "sequence: {"+ "timeTag: " + this.timeTag  + "}";
        }else{
            return "timeTag is null";
        }
    }

}
